//
//  HTMineViewController.m
//  TruckUser
//
//  Created by Ting Han on 2017/10/16.
//  Copyright © 2017年 Ting Han. All rights reserved.
//

#import "HTMineViewController.h"
#import "HTRegisterFirstStepVC.h"
#import "HTWayBillVC.h"
#import "HTLoginVC.h"
#import "UIImageView+WebCache.h"
#import "HTNotificationVC.h"
#import "HTMineViewCell.h"
#import "HTMineDetialModel.h"
#import "HTImageClipViewController.h"

@interface HTMineViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UITableViewDelegate,UITableViewDataSource,HTImageClipViewControllerDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (strong, nonatomic) IBOutlet UIView *headerViewAfter;
@property (weak, nonatomic) IBOutlet UIImageView *headImageView;
@property (weak, nonatomic) IBOutlet UILabel *checkLabel;
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
@property (weak, nonatomic) IBOutlet UILabel *phoneLabel;
@property (weak, nonatomic) IBOutlet UILabel *companyLabel;

@property (strong, nonatomic) IBOutlet UIView *headerViewBefore;

@property (weak, nonatomic) IBOutlet UIImageView *logoImageView;

@property (weak, nonatomic) IBOutlet UILabel *messageLabel;
@property (weak, nonatomic) IBOutlet UIButton *toRegisterButton;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *safeBottomHeight;

@property (nonatomic,strong) NSArray *dataSource;
@property (nonatomic,assign) CGFloat headerTableHeight;
@property (nonatomic,assign) BOOL isFromUpImage;
@property (nonatomic,strong) HTMineInfoModel *mineInfoModel;
@end

@implementation HTMineViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self configTableView];
    self.isFromUpImage = NO;
    self.checkLabel.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(didRegister:)];
    [self.checkLabel addGestureRecognizer:tap];
    self.safeBottomHeight.constant = IPHONE_SAFEBOTTOMAREA_HEIGHT + kHTToolBarHeight;
    self.headImageView.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapUploadHeadImage:)];
    [self.headImageView addGestureRecognizer:tap1];
    
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self netLoadUserInfo];
}
- (void)configTableView{
    self.dataSource = @[@"我的运单",@"我的消息",@"检查版本",@"退出登录"];
    self.tableView.delegate = self;
    self.tableView.dataSource =self;
    self.tableView.rowHeight = kWidth(55);
    [self.tableView registerNib:[UINib nibWithNibName:@"HTMineViewCell" bundle:nil] forCellReuseIdentifier:MineViewCell];
    self.headerTableHeight = 0;
}
- (void)tapUploadHeadImage:(id)sender{
    [self callActionSheetWithMessage:@"请您上传真实的头像"];
}
- (void)didRegister:(id)sender{
    if (self.mineInfoModel == nil) {
        [HTShowUtil showMessage:@"个人资料获取失败"];
        return;
    }
    HTRegisterFirstStepVC *first = [[HTRegisterFirstStepVC alloc]init];
    first.isRegister = [self.mineInfoModel.isaduit integerValue];
    [self.navigationController pushViewController:first animated:YES];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (self.mineInfoModel == nil || self.mineInfoModel.isaduit == nil) {
        self.headerTableHeight = 0;
        return 0;
    }
    //isaduit  0: 未审核  1:认证中 2：已通过 3：未通过
    if (!([self.mineInfoModel.isaduit integerValue] == 2)) {
        self.headerTableHeight = 280;
        return 280;
    }else{
        self.headerTableHeight = 300;
        return 300;
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (self.mineInfoModel == nil || self.mineInfoModel.isaduit == nil) {
        return nil;
    }
   //isaduit  0: 未审核  1:认证中 2：已通过 3：未通过
    if ([self.mineInfoModel.isaduit integerValue] == 2) {
        self.headImageView.layer.masksToBounds = YES;
        self.headImageView.layer.cornerRadius = kWidth(40);
        return self.headerViewAfter;
    }else{
        return self.headerViewBefore;
    }
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    HTMineViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MineViewCell forIndexPath:indexPath];
    [cell.titleButton setTitle:self.dataSource[indexPath.row] forState:UIControlStateNormal];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    switch (indexPath.row) {
        case 0://我的运单
        {
            HTWayBillVC *waybill = [[HTWayBillVC alloc]init];
            [self.navigationController pushViewController:waybill animated:YES];
        }
            break;
        case 1://我的消息
        {
            HTNotificationVC *notif = [[HTNotificationVC alloc]init];
            [self.navigationController pushViewController:notif animated:YES];
        }
            break;
        case 2://检查版本
        {
            NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
            NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
            [UIAlertController alertStyleShowInController:self title:@"温馨提示" message: [NSString stringWithFormat:@"当前版本号为%@",app_Version] alertActionsBlock:^(NSMutableArray<UIAlertAction *> *alertActions) {
                [alertActions addObject:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil]];
            } completion:^{
                
            }];
        }
            break;
        case 3://退出登录
        {
            UIAlertView * alert = [[UIAlertView alloc] initWithTitle:nil message:@"确认退出登录？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            [alert show];
        }
            break;
        default:
            break;
    }
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) {
        [HTUtils reLoginVC];
    }
}

- (void)callActionSheetWithMessage:(NSString *)message{
    [UIAlertController actionSheetStyleShowInController:self title:@"温馨提示" message:message alertActionsBlock:^(NSMutableArray<UIAlertAction *> *alertActions) {
        
        [alertActions addObject:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action){
            UIImagePickerController *PickerImage = [[UIImagePickerController alloc]init];
            PickerImage.sourceType = UIImagePickerControllerSourceTypeCamera;
            PickerImage.allowsEditing = NO;
            PickerImage.delegate = self;
            [self presentViewController:PickerImage animated:YES completion:nil];
        }]];
        [alertActions addObject:[UIAlertAction actionWithTitle:@"本地相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            UIImagePickerController *PickerImage = [[UIImagePickerController alloc]init];
            PickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            PickerImage.allowsEditing = NO;
            PickerImage.delegate = self;
            [self presentViewController:PickerImage animated:YES completion:nil];
        }]];
        [alertActions addObject:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    } completion:^{
        
    }];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    UIImage *portraitImg = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    HTImageClipViewController *imgCropperVC = [[HTImageClipViewController alloc] initWithImage:portraitImg cropFrame:CGRectMake(0, kWidth(90), self.view.frame.size.width, self.view.frame.size.width) limitScaleRatio:3.0];
    imgCropperVC.delegate = self;
    [picker pushViewController:imgCropperVC animated:NO];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)imageCropperDidCancel:(HTImageClipViewController *)clipViewController{
    [clipViewController dismissViewControllerAnimated:YES completion:nil];
}
- (void)imageCropper:(HTImageClipViewController *)clipViewController didFinished:(UIImage *)editedImage{
    self.isFromUpImage = YES;
    UIImage *imagenew =[self imageWithImageSimple:editedImage scaledToSize:CGSizeMake(240, 240)];
    [self netUpLoadPictureType:@"cargotitle" image:imagenew];
    [clipViewController dismissViewControllerAnimated:YES completion:nil];
    self.headImageView.image = editedImage;
}
- (IBAction)toRegistAction:(id)sender {
    if (self.mineInfoModel == nil || [self.mineInfoModel.isaduit integerValue] == 2 ) {
        return;
    }
    HTRegisterFirstStepVC *first = [[HTRegisterFirstStepVC alloc]init];
    first.isRegister = [self.mineInfoModel.isaduit integerValue];
    [self.navigationController pushViewController:first animated:YES];
}
#pragma mark --- 网络请求
- (void)netLoadUserInfo{
    [HTHttpRequestManager requestUserInfosuccess:^(id  _Nullable responseObject) {
        DBLog(@"个人信息：%@",responseObject);
        if (!responseObject) {
            [HTShowUtil showMessage:@"个人信息请求失败"];
            return ;
        }
        NSString *codeStr = [NSString stringWithFormat:@"%@",responseObject[@"code"]];
        if (![codeStr isEqualToString:@"200"]) {
            [HTShowUtil showMessage:responseObject[@"message"]];
            return;
        }
        self.mineInfoModel = [HTMineInfoModel mj_objectWithKeyValues:responseObject[@"data"]];
        [self.tableView reloadData];
    } failure:^(NSError * _Nonnull error) {
        [HTShowUtil showMessage:@"个人信息请求失败"];
    }];
}
- (void)netUpLoadPictureType:(NSString *)type image:(UIImage *)image{
    [self startHud];
    [HTHttpRequestManager requestUploadPictureWithType:type image:image success:^(id  _Nullable responseObject) {
        [self endHud];
        DBLog(@"上传图片：%@",responseObject);
        if (!responseObject) {
            [HTShowUtil showMessage:@"图片保存失败"];
            return ;
        }
        NSString *codeStr = [NSString stringWithFormat:@"%@",responseObject[@"code"]];
        if (![codeStr isEqualToString:@"200"]) {
            [HTShowUtil showMessage:responseObject[@"message"]];
            return;
        }
        self.headImageView.image = image;
        [HTShowUtil showMessage:responseObject[@"message"]];
    } failure:^(NSError * _Nonnull error) {
        [self endHud];
        [HTShowUtil showMessage:@"图片保存失败"];
    }];
}
- ( UIImage *)imageWithImageSimple:( UIImage *)image scaledToSize:( CGSize )newSize

{
    UIGraphicsBeginImageContext (newSize);
    
    [image drawInRect : CGRectMake ( 0 , 0 ,newSize. width ,newSize. height )];
    UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext ();
    UIGraphicsEndImageContext ();
    
    return newImage;
}


- (void)setMineInfoModel:(HTMineInfoModel *)mineInfoModel{
    _mineInfoModel = mineInfoModel;
    //isaduit  0: 未审核  1:认证中 2：已通过 3：未通过
    if ([mineInfoModel.isaduit integerValue] == 2) {
        if (self.isFromUpImage) {
            self.isFromUpImage = NO;
        }else{
             [self.headImageView sd_setImageWithURL:[NSURL URLWithString:mineInfoModel.userpic] placeholderImage:[UIImage imageNamed:@"bg_headsculpture"]options:SDWebImageRefreshCached];
        }
        self.nameLabel.text = mineInfoModel.usename;
        self.phoneLabel.text = mineInfoModel.phone;
        self.companyLabel.text = mineInfoModel.companyname;
    }else{
         self.messageLabel.text = [NSString stringWithFormat:@"%@",mineInfoModel.resut];
        if ([mineInfoModel.isaduit integerValue] == 0) {//未认证
            self.toRegisterButton.enabled = YES;
            [self.toRegisterButton setTitle:@"去认证" forState:UIControlStateNormal];
        }else if([mineInfoModel.isaduit integerValue] == 1){//认证中
            self.toRegisterButton.enabled = NO;
            [self.toRegisterButton setTitle:@"认证中" forState:UIControlStateNormal];
        }else if([mineInfoModel.isaduit integerValue] == 3){//认证不通过
            self.toRegisterButton.enabled = YES;
            [self.toRegisterButton setTitle:@"修改信息" forState:UIControlStateNormal];
        }
    }
}
@end
@implementation HTMineInfoModel

@end
